package com.jmu.edu.IMApplication.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.github.chrisbanes.photoview.PhotoView;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.net.bean.UserTag;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.model.UserInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ShowUserFragment extends Fragment {
    private static final String TAG = "showUser";
    private MaterialButton addFriendButton, sendMessageButton, backButton, moreButton, tagButton;
    private ShapeableImageView avatarImage;
    private FlexboxLayout flexboxLayout;
    private TextView nameText, signText;
    private UserInfo userInfo;
    private String backTag = null;
    private List<UserTag> userTagList;

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    public ShowUserFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_show_user, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        addFriendButton = getView().findViewById(R.id.fragment_show_user_add_friend);
        sendMessageButton = getView().findViewById(R.id.fragment_show_user_send_message);
        backButton = getView().findViewById(R.id.fragment_show_user_back);
        moreButton = getView().findViewById(R.id.fragment_show_user_more);
        tagButton = getView().findViewById(R.id.fragment_show_user_tag);
        flexboxLayout = getView().findViewById(R.id.fragment_show_user_flex_box);
        nameText = getView().findViewById(R.id.fragment_show_user_message_name);
        signText = getView().findViewById(R.id.fragment_show_user_message_sign);
        avatarImage = getView().findViewById(R.id.fragment_show_user_avatar);
        initListener();
        loadData();
        ViewUtils.addBackListenerForHide(getView(), backButton);


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {

        } else {
            loadData();
            ViewUtils.addBackListenerForHide(getView(), backButton);
        }
    }

    private void loadData() {
        Bundle bundle = getArguments();
        // 默认回退到searchFriend
        if (bundle != null) {
            backTag = bundle.getString("backTag", "searchFriend");
        } else {
            backTag = "searchFriend";
        }
        fillViewWithValues();
        //向服务器请求获得标签数据
        RequestBody requestBody = RequestBody.create(null, "");
        String url = HttpUtil.URL_GET_USER_TAG + "?username=" + userInfo.getUserName();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                TypeToken<List<UserTag>> typeToken = new TypeToken<List<UserTag>>() {
                };
                //将json数据转化为实体类
                userTagList = new Gson().fromJson(json, typeToken.getType());
                // 如果为空就说明没有标签，不需要执行下面标签显示的代码
                if (userTagList == null) {
                    return;
                }
                //装载数据前先将flexBox中原本添加的tag删除
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        flexboxLayout.removeAllViews();
                        loadFlexBoxData();
                    }
                });

            }
        });

    }

    private void loadFlexBoxData() {
        //将标签数据显示在flexBox
        int size = userTagList.size();
        //一次只显示6个数据 （0~5是6个数据）
        if (size > 5) {
            size = 5;
        }
        for (int i = 0; i < size; i++) {
            flexboxLayout.addView(ViewUtils.getTagItemView(getLayoutInflater(), userTagList.get(i).getTag(), i, getResources(), false));
        }
    }

    private void fillViewWithValues() {
        //获取头像
        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    Glide.with(avatarImage).load(bitmap).into(avatarImage);
                } else {
                    Glide.with(avatarImage).load(R.drawable.smc).into(avatarImage);
                }
            }
        });
        //如果是好友则隐藏"添加好友"按钮,显示"更多"按钮
        if (userInfo.isFriend()) {
            addFriendButton.setVisibility(View.GONE);
            moreButton.setVisibility(View.VISIBLE);
        } else {
            addFriendButton.setVisibility(View.VISIBLE);
            moreButton.setVisibility(View.GONE);
        }
        nameText.setText(WillowUtils.getNickName(userInfo));
        signText.setText(WillowUtils.getCompleteSignature(userInfo));
    }

    private void initListener() {
        addFriendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = "addFriend";
                AddFriendFragment addFriendFragment = (AddFriendFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                if (addFriendFragment == null) {
                    addFriendFragment = new AddFriendFragment();
                }
                //传递必须的参数
                addFriendFragment.setUserInfo(userInfo);
                Bundle bundle = new Bundle();
                bundle.putString("backTag", "showUser");
                addFriendFragment.setArguments(bundle);
                ViewUtils.showFragment(addFriendFragment, tag);
            }
        });
        sendMessageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = "chat";
                ChatFragment chatFragment = (ChatFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                if (chatFragment == null) {
                    chatFragment = new ChatFragment();
                }
                //传递必须的参数
                Bundle bundle = new Bundle();
                bundle.putString("username", userInfo.getUserName());
                bundle.putString("friendName", WillowUtils.getNickName(userInfo));
                bundle.putString("state", "在线");
                bundle.putString("backTag", "showUser");
                chatFragment.setArguments(bundle);

                ViewUtils.hideFragment(ShowUserFragment.this, chatFragment, tag, R.anim.from_right, R.anim.out_left);
            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (backTag == null) {
                    ViewUtils.hideFragment(ShowUserFragment.this);
                } else {
                    // 根据backTag来决定隐藏后显示的是哪个Fragment
                    Fragment fragment = MyApplication.fragmentManager.findFragmentByTag(backTag);
                    ViewUtils.hideFragment(ShowUserFragment.this, fragment, backTag, R.anim.from_left, R.anim.out_right);
                }
            }
        });
        tagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = "showTag";
                ShowTagFragment showTagFragment = (ShowTagFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                if (showTagFragment == null) {
                    showTagFragment = new ShowTagFragment();
                }
                showTagFragment.setUserInfo(userInfo);
                //添加backTag来设置到时候回退展示的是哪一个Fragment
                Bundle bundle = new Bundle();
                bundle.putString("backTag", "showUser");
                showTagFragment.setArguments(bundle);
                ViewUtils.hideFragment(ShowUserFragment.this, showTagFragment, tag, R.anim.from_right, R.anim.out_left);
            }
        });
    }
}